﻿using System;
using System.Linq;
using System.Windows.Forms;
using HostServicePhoneCommands.Properties;

namespace HostServicePhoneCommands
{
    public partial class CreateSnapshotHyperV : Form
    {
        public string NameMachine { get; set; }

        public CreateSnapshotHyperV()
        {
            InitializeComponent();
        }

        private void CreateSnapshotHyperVShown(object sender, EventArgs e)
        {
            LblVmMachine.Text = NameMachine;
            Lblresult.Text = string.Empty;
        }

        private void GenerateName()
        {
            var result = TxtName.Text.Trim();
            if (result.Length != 0)
            {
                if (ChkDateTime.Checked)
                {
                    result += " (" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ")";
                }
            }
            Lblresult.Text = result;
        }

        private void TxtNameTextChanged(object sender, EventArgs e)
        {
            GenerateName();
        }

        private void ChkDateTimeCheckStateChanged(object sender, EventArgs e)
        {
            GenerateName();
        }

        private void BntOkClick(object sender, EventArgs e)
        {
            if (TxtName.Text.Length == 0)
            {
                MessageBox.Show(Resources.CreateSnapshotHyperVNameEmpty, Resources.NameApp, MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }
            Cursor = Cursors.WaitCursor;

            var itemset = Settings.Default.StartSnapshot.Cast<string>().FirstOrDefault(d => d.StartsWith(NameMachine + "|"));
            if (ChkDefault.Checked)
            {
                //default start (use compensation)
                if (itemset != null)
                {
                    Settings.Default.StartSnapshot.Remove(itemset);
                }
                Settings.Default.StartSnapshot.Add(NameMachine + "|" + Lblresult.Text);
                Settings.Default.Save();
            }

            var cmd = Program.PhoneService.CreateSnapshot(NameMachine, Lblresult.Text);
            Cursor = Cursors.Default;
            if (cmd.Successful)
            {
                Close();
            }
            else
            {
                if (ChkDefault.Checked)
                {
                    //compensation (roolback default)
                    Settings.Default.StartSnapshot.Remove(NameMachine + "|" + Lblresult.Text);
                    if (itemset != null)
                    {
                        Settings.Default.StartSnapshot.Add(itemset);
                    }
                    Settings.Default.Save();
                }
                MessageBox.Show(cmd.ErrorMessage, Resources.NameApp, MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }
    }
}
